import { AnyObj } from './types'

export function getValue(target: AnyObj, str: string) {
    let keys = str.split(".");
    let result = target;
    for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        if (key in result) {
            if (i === keys.length - 1) {
                return result[key]
            }

            result = result[key];
            if (typeof result !== 'object' && i < keys.length - 1) {
                throw new Error(`please check the key ${str}`)
            }
        } else {
            throw new Error(`please check the key ${str}`)
        }
    }
}

export function setValue(target: AnyObj, str: string, value: any) {
    let keys = str.split(".");
    let result = target;
    for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        if (key in result) {
            if (i === keys.length - 1) {
                result[key] = value
                return
            }

            result = result[key];
            if (typeof result !== 'object' && i < keys.length - 1) {
                throw new Error(`please check the key ${str}`)
            }
        } else {
            throw new Error(`please check the key ${str}`)
        }
    }
}